package com.spice.service.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.spice.common.constant.PermissionConstant;
import com.spice.common.util.DateUtil;
import com.spice.common.util.MD5;
import com.spice.common.util.PermissionUtil;
import com.spice.service.entity.pojo.Authorization;
import com.spice.service.entity.pojo.User;
import com.spice.service.service.AuthorizationService;
import com.spice.service.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * @author yhm
 * shiro认证与授权
 */

public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;
    @Autowired
    AuthorizationService authorizationService;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        String username = SecurityUtils.getSubject().getPrincipal().toString();
        User user = userService.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username));

        info.addRole(user.getStatus());
        // 判断身份
        if (PermissionConstant.ROOT_ROLE.equals(user.getStatus())) {
            // 超级管理员
            for (String permission : PermissionUtil.getAllPermission()) {
                info.addObjectPermission(getPermissionResolver()
                        .resolvePermission(permission));
            }
        } else if (PermissionConstant.PRODUCT_CENTER_DIRECTOR_ROLE.equals(user.getStatus())) {
            // 产品中心总监
            for (String permission : PermissionUtil.getProductCenterPermission()) {
                info.addObjectPermission(getPermissionResolver()
                        .resolvePermission(permission));
            }
        } else if (PermissionConstant.QUALITY_CENTER_DIRECTOR_ROLE.equals(user.getStatus())) {
            // 质量中心总监
            for (String permission : PermissionUtil.getQualityCenterPermission()) {
                info.addObjectPermission(getPermissionResolver()
                        .resolvePermission(permission));
            }
        } else if (PermissionConstant.PRODUCT_CENTER_WORKER_ROLE.equals(user.getStatus())
                || PermissionConstant.QUALITY_CENTER_WORKER_ROLE.equals(user.getStatus())) {
            // 产品中心专员、质量中心专员
            for (Authorization authorization : authorizationService.getBaseMapper()
                    .selectList(new LambdaQueryWrapper<Authorization>()
                            .eq(Authorization::getUserId, user.getId()))) {
                info.addObjectPermission(getPermissionResolver()
                        .resolvePermission(authorization.getPermission()));
            }
        }
        return info;
    }


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        String password = MD5.encrypt(new String((char[]) token.getCredentials()));
        String verificationCode = new String((char[]) token.getCredentials());

        User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
        if (user != null) {
            if (password.equals(user.getPassword())) {
                user.setLastLoginTime(DateUtil.getNowDateTime());
                userService.updateById(user);
                return new SimpleAuthenticationInfo(username, verificationCode, getName());
            } else {
                throw new IncorrectCredentialsException();
            }
        } else {
            throw new UnknownAccountException("未知用户名:" + username);
        }


//        throw new IncorrectCredentialsException();
//        throw new UnknownAccountException("未知用户名:" + username);
//        throw new RuntimeException("数据库出现重复用户");
    }
}
